package com.powerunion.datacollection.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.Format;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.SubmissionWorkItemDao;
import com.powerunion.datacollection.model.ActivityInfo;
import com.powerunion.datacollection.model.SubmissionWorkItem;
import com.powerunion.datacollection.model.Urgency;
import com.powerunion.datacollection.model.jsonObject.TaskInfo;
import com.powerunion.datacollection.model.jsonObject.TaskTrackDetails;
import com.powerunion.datacollection.persistence.db.jdbc.operator.QueryOperator;
import com.powerunion.datacollection.persistence.db.jdbc.operator.RsDataSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameter;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameterSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlType;
import com.powerunion.datacollection.persistence.db.jdbc.operator.UpdateOperator;
import com.powerunion.datacollection.quartz.TaskScheduler;
import com.powerunion.datacollection.service.SmsManager;
import com.powerunion.datacollection.service.UrgencyManager;
import com.powerunion.util.DBUtils;
import com.powerunion.util.log.LogHelper;

public class SubmissionWorkItemDaoImpl extends JdbcBase implements
		SubmissionWorkItemDao {
	// 初始化日志类
	private static final Logger logger = LogHelper.getInstance().getLogger(
			SubmissionWorkItemDaoImpl.class);

	protected String sqlInsert() {
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"insert into dc_submission_work(id,proc_id,sw_desc,sw_name,act_id,sw_state,sw_type,staff_id,")
				.append(
						"time_limit,date_urge,form_id,create_date,work_type) values(?,?,?,?,?,?,?,?,?,?,?,sysdate,1)");
		return sql.toString();
	}

	private boolean delete(String actId, Connection conn) throws DaoException {
		String sql = "delete from dc_submission_work where act_id=? and sw_type = 8";
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql);
		update.setUseOnlyConnectionFlag(true);
		update.setPresentConnection(conn);
		update.addParameter(new SqlParameter(SqlType.VARCHAR, actId));
		try {
			update.access();
		} catch (Exception e) {
			logger.error("删除审批人的报送信息出错！", e);
			throw new DaoException("删除审批人的报送信息出错！");
		}

		int effectCount = update.getEffectCounts();
		if (effectCount > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("delete:" + "删除审批人的报送信息出错" + Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("delete:" + "删除审批人的报送信息出错" + Constants.FAIL);
			}
			return false;
		}

	}

	public boolean save(ActivityInfo activityInfo, String formId,
			Connection conn) throws DaoException {
		boolean flag = false;
		try {
			String usersStr = activityInfo.getExamineUserOrcollectionUser();
			String[] users = StringUtils.split(usersStr, ",");
			String userTypesStr = activityInfo
					.getExamineUserOrcollectionUserTypes();
			String[] userTypes = StringUtils.split(userTypesStr, ",");

			if (users != null && users.length > 0) {
				for (int j = 0; j < users.length; j++) {
					String userCode = users[j];
					String userType = userTypes[j];
					if (!StringUtils.isEmpty(userType)) {
						if (userType.equals("user")) {
							String[] userCodes = new String[1];
							userCodes[0] = userCode;
							this.initSubWork(userCodes, activityInfo, formId,
									conn);
						} else if (userType.equals("group")) {
							String[] gorupUserCodes = this.getUserCodeByGroup(
									userCode, conn);
							this.initSubWork(gorupUserCodes, activityInfo,
									formId, conn);
						} else if (userType.equals("department")) {
							String[] deptUserCodes = this.getUserCodeByDept(
									userCode, conn);
							this.initSubWork(deptUserCodes, activityInfo,
									formId, conn);
						}
					}

				}
				flag = true;
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("保存报送明细信息失败！");
		}

		return flag;
	}

	public boolean initSubWork(String[] userCodes, ActivityInfo activityInfo,
			String formId, Connection conn) throws DaoException {

		String sql = this.sqlInsert();

		UpdateOperator update = new UpdateOperator();
		update.setSql(sql);
		update.setUseOnlyConnectionFlag(true);
		update.setPresentConnection(conn);

		try {

			if (userCodes != null && userCodes.length > 0) {
				UrgencyManager um = new UrgencyManager();
				SmsManager sm = new SmsManager();
				for (int j = 0; j < userCodes.length; j++) {
					String userCode = userCodes[j];

					SqlParameterSet spSet = new SqlParameterSet();
					String id = String.valueOf(this
							.getSeq("dc_submission_work"));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR, id));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR,
							activityInfo.getProcId()));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR,
							activityInfo.getDescription()));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR,
							activityInfo.getActivityName()));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR,
							activityInfo.getActivityId()));
					spSet.addParameter(new SqlParameter(SqlType.INTEGER,
							new Integer(0)));
					spSet
							.addParameter(new SqlParameter(SqlType.INTEGER,
									new Integer(activityInfo
											.getFillTypeOrapproveType())));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR,
							userCode));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR,
							activityInfo.getTimeLimit()));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR,
							activityInfo.getApproveUserOrurgencyDate()));
					spSet
							.addParameter(new SqlParameter(SqlType.VARCHAR,
									formId));

					// 把提醒信息保存到短信表里，进行短信通知
					Urgency uc = um
							.getBykey(activityInfo.getActivityId(), conn);
					String msg = uc.getRemindInfo();
					if (!StringUtils.isEmpty(msg)) {
						sm.saveSMS(conn, msg, userCode);
					}

//					String urgenContent = uc.getUrgencyContent();
//					if (!StringUtils.isEmpty(urgenContent)) {
//						String urgeTime = uc.getUrgeTime().substring(0, 10);
//						String[] urgeDate = StringUtils.split(urgeTime, "-");
//						if (urgeDate != null && urgeDate.length == 3) {
//							JobDetail jd = new JobDetail();
//							jd.getJobDataMap()
//									.put("urgenContent", urgenContent);
//							jd.getJobDataMap().put("userCode", userCode);
//							jd.getJobDataMap().put("id", id);
//							jd.getJobDataMap().put(
//											"type",
//											String.valueOf(Constants.TASK_TYPE_SUBMISSIONWORK));
//							StringBuffer taskName = new StringBuffer();
//							taskName.append(id).append("_sw_urgen");
//							jd.getJobDataMap().put("taskName", taskName.toString());
//
//							java.util.Calendar cal = new java.util.GregorianCalendar(
//									Integer.parseInt(urgeDate[0]), Integer
//											.parseInt(urgeDate[1])==0?0:Integer
//													.parseInt(urgeDate[1])-1, Integer
//											.parseInt(urgeDate[2]));
//							// 固定早上10点发送催办信息
//							cal.set(cal.HOUR, 10);
//							cal.set(cal.MINUTE, 0);
//							cal.set(cal.SECOND, 0);
//							cal.set(cal.MILLISECOND, 0);
//							Date startTime = cal.getTime();
//
//							int repeatIntervalDay = uc.getRepeatIntervalDay();
//							int repeatIntervalHour = uc.getRepeatIntervalHour();
//
//							long repeatInterval = 86400L * repeatIntervalDay
//									+ 3600L * repeatIntervalHour;
//
//							if (repeatInterval == 0) {
//								//当repeatInterval=0的时候会报错！
//								repeatInterval = 1;
//							}
//							
//							TaskScheduler.getInstance().schedule(
//									UrgencyTask.class, taskName.toString(),
//									startTime,null, uc.getRepeatCount(),
//									repeatInterval * 1000L, jd);
//						}
//					}

					update.addBatchParameter(spSet);
				}
				update.access();
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("保存报送明细信息失败！");
		}

		int[] effectCount = update.getBatchEffectCounts();
		if (effectCount != null && effectCount.length > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "报送明细信息"
						+ Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "报送明细信息"
						+ Constants.FAIL);
			}
			return false;
		}

	}

	public boolean initSubWork(String userCode, ActivityInfo activityInfo,
			String formId) throws DaoException {

		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"insert into dc_submission_work(id,proc_id,sw_desc,sw_name,act_id,sw_state,sw_type,staff_id,")
				.append(
						"time_limit,date_urge,form_id,create_date,work_type) values(?,?,?,?,?,?,?,?,?,?,?,sysdate,1)");

		Connection conn = null;
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql.toString());

		try {
			conn = this.getConnection();
			// 先删除原有的记录
			this.delete(activityInfo.getActivityId(), conn);
			update.setPresentConnection(conn);
			update.setUseOnlyConnectionFlag(true);
			String id = String.valueOf(this.getSeq("dc_submission_work"));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, id));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, activityInfo
					.getProcId()));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, activityInfo
					.getDescription()));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, activityInfo
					.getActivityName()));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, activityInfo
					.getActivityId()));
			update.addParameter(new SqlParameter(SqlType.INTEGER,
					new Integer(0)));
			update.addParameter(new SqlParameter(SqlType.INTEGER, new Integer(
					activityInfo.getFillTypeOrapproveType())));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, userCode));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, activityInfo
					.getTimeLimit()));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, activityInfo
					.getApproveUserOrurgencyDate()));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, formId));

			update.access();

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("保存报送明细信息失败！");
		} finally {
			DBUtils.close(conn);
		}

		int effectCount = update.getEffectCounts();
		if (effectCount > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "报送明细信息"
						+ Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "报送明细信息"
						+ Constants.FAIL);
			}
			return false;
		}

	}

	private String[] getUserCodeByGroup(String groupId, Connection conn)
			throws DaoException {
		String sql = "select user_code from user_group where grop_code = ? ";
		String[] userCodes = null;
		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);
		query.addParameter(new SqlParameter(SqlType.VARCHAR, groupId));
		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {

					userCodes = new String[rs.rowCount];
					for (int i = 0; i < rs.rowCount; i++) {
						String userCode = rs.getFieldValueAsString("user_code");
						userCodes[i] = userCode;

						rs.next();
					}
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getUserCodeByGroup throw error!");
		}
		return userCodes;
	}

	private String[] getUserCodeByDept(String deptId, Connection conn)
			throws DaoException {
		String sql = "select user_code from user_dept where fram_seq = ? ";
		String[] userCodes = null;
		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);
		query.addParameter(new SqlParameter(SqlType.VARCHAR, deptId));
		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {
					userCodes = new String[rs.rowCount];
					for (int i = 0; i < rs.rowCount; i++) {
						String userCode = rs.getFieldValueAsString("user_code");
						userCodes[i] = userCode;

						rs.next();
					}
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getUserCodeByDept throw error!");
		}
		return userCodes;
	}

	/**
	 * 查找该用户当前的采集任务
	 * 
	 * @param userCode
	 * @return
	 */
	public List findSubmissionWorkByUser(String userCode) throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select s.id,s.proc_id,t.item_name,w.wf_instance_desc,w.wf_name,")
				.append(
						"s.act_id,s.staff_id,s.time_limit,s.form_id,s.sw_state, s.sw_name ")
				.append(
						" from dc_item_info t left join dc_submission_work s on s.proc_id = t.id ")
				.append(
						" left join dc_wf_instance w on t.id = w.proc_id  where s.staff_id = ? and sw_state <> 5")
				.append(
						"  and  sw_state <> 6 and  sw_state <> 4 and  sw_state <> 2 and  sw_state <> 8 and sw_type <> 8 ");

		List submissionWorkList = null;

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, userCode));

		try {
			submissionWorkList = new ArrayList();
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					TaskInfo swi = new TaskInfo();
					swi.setId(rs.getFieldValueAsString("id"));
					swi.setProcId(rs.getFieldValueAsString("proc_id"));
					swi.setProcName(rs.getFieldValueAsString("item_name"));
					swi.setTaskDesc(rs
							.getFieldValueAsString("wf_instance_desc"));
					swi.setTaskName(rs.getFieldValueAsString("wf_name"));
					swi.setActId(rs.getFieldValueAsString("act_id"));
					swi.setType(Constants.TASK_TYPE_SUBMISSIONWORK);
					swi.setStaffId(rs.getFieldValueAsString("staff_id"));
					swi.setTimeLimitStr(rs.getFieldValueAsString("time_limit"));
					swi.setFormId(rs.getFieldValueAsString("form_id"));
					swi.setState(rs.getFieldValueAsInteger("sw_state")
							.intValue());
					swi.setPreActName(rs.getFieldValueAsString("sw_name"));

					submissionWorkList.add(swi);

					rs.next();
				}

				rs.clearAll();
			}

		} catch (Exception e) {
			logger.error("查找用户编码为：" + userCode + "的当前采集任务失败！", e);
			throw new DaoException("查找用户编码为：" + userCode + "的当前采集任务失败！");
		}

		return submissionWorkList;
	}

	/**
	 * 更新报送明细状态
	 * 
	 * @param state
	 * @param actId
	 * @return
	 */
	public boolean updateState(int state, String actId) throws DaoException {
		String sql = "update dc_submission_work set sw_state=? where act_id = ? and sw_state<>8";
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql);
		update.addParameter(new SqlParameter(SqlType.INTEGER,
				new Integer(state)));
		update.addParameter(new SqlParameter(SqlType.VARCHAR, actId));

		try {
			update.access();
		} catch (Exception e) {
			logger.error("更新环节id为：" + actId + " 的报送明细状态失败！", e);
			throw new DaoException("更新环节id为：" + actId + " 的报送明细状态失败！");
		}

		int effectCount = update.getEffectCounts();
		if (effectCount > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("updateState:" + Constants.UPDATE + "报送明细状态"
						+ Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("updateState:" + Constants.UPDATE + "报送明细状态"
						+ Constants.FAIL);
			}
			return false;
		}

	}

	public boolean updateState4User(int state, String idStr)
			throws DaoException {
		String sql = "update dc_submission_work set sw_state=?,update_date=sysdate where id = ? ";
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql);

		try {
			String[] ids = StringUtils.split(idStr, ",");
			if (ids != null && ids.length > 0) {
				for (int j = 0; j < ids.length; j++) {
					String id = ids[j];
					SqlParameterSet spSet = new SqlParameterSet();
					spSet.addParameter(new SqlParameter(SqlType.INTEGER,
							new Integer(state)));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR, id));

					update.addBatchParameter(spSet);
				}
				update.access();
			}
		} catch (Exception e) {
			logger.error("更新报送任务报送明细状态失败！", e);
			throw new DaoException("更新报送任务报送明细状态失败！");
		}

		int[] effectCount = update.getBatchEffectCounts();
		if (effectCount != null && effectCount.length > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("updateState4User:" + Constants.UPDATE
						+ "报送任务报送明细状态" + Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("updateState4User:" + Constants.UPDATE
						+ "报送任务报送明细状态" + Constants.FAIL);
			}
			return false;
		}

	}

	public boolean resumeSubmissionWork(String procId) throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append("update dc_submission_work set sw_state = ")
				.append(
						"(select state_track from dc_submission_work where id = ?) where id = ? and sw_type <> 8 ");
		Connection conn = null;
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql.toString());
		update.setUseOnlyConnectionFlag(true);
		update.setPresentConnection(conn);
		try {
			conn = this.getConnection();
			List ids = this.findSubmissionWorkIdByProcId(procId, conn);
			this.resumeUrgencyTask(conn, ids);
			if (ids != null && ids.size() > 0) {
				for (Iterator iter = ids.iterator(); iter.hasNext();) {
					SqlParameterSet spSet = new SqlParameterSet();
					String id = (String) iter.next();
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR, id));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR, id));

					update.addBatchParameter(spSet);
				}
				update.access();
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("resumeSubmissionWork error!");
		}
		int[] effectCount = update.getBatchEffectCounts();
		if (effectCount != null && effectCount.length > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("resumeSubmissionWork success!");
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("resumeSubmissionWork failure!");
			}
			return false;
		}
	}

	/**
	 * 	恢复催办任务
	 * @param procId
	 * @param conn
	 * @param ids
	 * @throws DaoException
	 */
	private void  resumeUrgencyTask(Connection conn,List ids) throws DaoException {
		for(int i=0;i<ids.size();i++){
			String id = (String)ids.get(i);
			String taskName = id+"_sw_urgen";
			TaskScheduler.getInstance().resumeTask(taskName);
		}
	}
	
	public boolean suspendSubmissionWork(String procId) throws DaoException {
		String sql = "update dc_submission_work set sw_state=6 where proc_id =? and sw_state <> 8 and sw_type <> 8 ";
		Connection conn = null;
		PreparedStatement ps = null;
		boolean flag = false;
		try {
			conn = this.getConnection();

			List ids = this.findSubmissionWorkIdByProcId(procId, conn);
			this.suspendUrgencyTask(conn,ids);
			this.backupState(ids, conn);

			// 更改报送明细表状态
			ps = conn.prepareStatement(sql);
			ps.setString(1, procId);
			ps.executeUpdate();
			flag = true;
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("suspendSubmissionWork error!");
		} finally {
			DBUtils.close(ps, conn);
		}
		return flag;
	}
	/**
	 * 暂停催办任务
	 * @param procId
	 * @param conn
	 * @param ids
	 * @throws DaoException
	 */
	private void  suspendUrgencyTask(Connection conn,List ids) throws DaoException {
		for(int i=0;i<ids.size();i++){
			String id = (String)ids.get(i);
			String taskName = id+"_sw_urgen";
			TaskScheduler.getInstance().pauseTask(taskName);
		}
	}

	private boolean backupState(List ids, Connection conn) throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append("update dc_submission_work set state_track= ")
				.append(
						"(select sw_state from dc_submission_work where id = ?) where id = ? and sw_type <> 8 ");
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql.toString());
		update.setUseOnlyConnectionFlag(true);
		update.setPresentConnection(conn);
		try {
			if (ids != null && ids.size() > 0) {
				for (Iterator iter = ids.iterator(); iter.hasNext();) {
					SqlParameterSet spSet = new SqlParameterSet();
					String id = (String) iter.next();
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR, id));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR, id));

					update.addBatchParameter(spSet);
				}
				update.access();
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("backupState error!");
		}
		int[] effectCount = update.getBatchEffectCounts();
		if (effectCount != null && effectCount.length > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("backupState success!");
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("backupState failure!");
			}
			return false;
		}

	}

	private List findSubmissionWorkIdByProcId(String procId, Connection conn)
			throws DaoException {
		String sql = "select id from dc_submission_work where proc_id = ? and sw_type <> 8 ";

		QueryOperator query = new QueryOperator();
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);
		query.setSql(sql);
		query.addParameter(new SqlParameter(SqlType.VARCHAR, procId));
		List list = null;
		try {

			list = new ArrayList();
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					String id = rs.getFieldValueAsString("id");

					list.add(id);

					rs.next();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("findSubmissionWorkIdByProcId error!");
		}
		return list;
	}

	/**
	 * 判断是否能提交报送数据到上级审批步骤
	 * 
	 * @param procId
	 * @param actId
	 * @return
	 * @throws DaoException
	 */
	public boolean submissionRule(String actId) throws DaoException {
		Connection conn = null;
		boolean flag = false;
		try {
			conn = this.getConnection();
			int actType = this.getActivityType(actId);
			if (actType == Constants.SUBMISSION_TYPE_SINGLE) {// 单人类型
				/**
				 * 单人类型 需要判断该环节的其他人是否已经提交过了， 如果已经有人提交过了则不能提交
				 */
				int count = this.getCountActivityComplete(actId, conn);
				if (count > 0) {
					flag = false;
				} else {
					flag = true;
				}
			} else if (actType == Constants.SUBMISSION_TYPE_MULTI) {//
				/**
				 * 多人类型 需要判断该环节的其他人的提交状态， 如果其他人都处于提交并等待其他人的状态下则提交 否则不能提交
				 */
				int totalWaitingUser = this
						.getCountActivityWaiting(actId, conn);
				int totalActUser = this.getCountActivityTotalUser(actId, conn);
				// 当其他人都已经填写完审批意见处于等待状态的情况下就可以提交到上级节点去
				if (totalWaitingUser == totalActUser - 1) {
					flag = true;
				} else {
					flag = false;
				}
			}
		} catch (Exception e) {
			logger.error("", e);
		} finally {
			DBUtils.close(conn);
		}
		return flag;
	}

	private int getCountActivityComplete(String actId, Connection conn)
			throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select count(id) c from dc_submission_work where act_id = ? and sw_state <> 9 and sw_state <> 0 ")
				.append(
						"  and sw_state <>1 and sw_state<> 2 and sw_state <> 3 and sw_state <> 7 and sw_state <> 8 and sw_type <> 8 ");

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);
		query.addParameter(new SqlParameter(SqlType.VARCHAR, actId));
		int count = 0;
		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {
					count = rs.getFieldValueAsInteger("c").intValue();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getActivityType error!");
		}
		return count;
	}

	public int getActivityType(String actId) throws DaoException {
		String sql = "select distinct(sw_type) from dc_submission_work where act_id = ? and sw_type <> 8 ";
		QueryOperator query = new QueryOperator();
		query.setSql(sql);

		query.addParameter(new SqlParameter(SqlType.VARCHAR, actId));
		int swType = 0;
		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {
					swType = rs.getFieldValueAsInteger("sw_type").intValue();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getActivityType error!");
		}

		return swType;
	}

	/**
	 * 得到处于等待状态的用户个数
	 * 
	 * @param actId
	 * @param conn
	 * @return
	 * @throws DaoException
	 */
	private int getCountActivityWaiting(String actId, Connection conn)
			throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql.append(
				"select count(id) c from dc_submission_work where act_id = ? ")
				.append("  and sw_state = 2  and sw_type <> 8 ");

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);
		query.addParameter(new SqlParameter(SqlType.VARCHAR, actId));
		int count = 0;
		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {
					count = rs.getFieldValueAsInteger("c").intValue();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getCountActivityWaiting error!");
		}
		return count;
	}

	/**
	 * 该步骤报送人员的个数
	 * 
	 * @param actId
	 * @param conn
	 * @return
	 * @throws DaoException
	 */
	private int getCountActivityTotalUser(String actId, Connection conn)
			throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append("select count(id) c from dc_submission_work where act_id = ?  and sw_type <> 8 ");

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);
		query.addParameter(new SqlParameter(SqlType.VARCHAR, actId));
		int count = 0;
		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {
					count = rs.getFieldValueAsInteger("c").intValue();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getCountActivityTotalUser error!");
		}
		return count;
	}

	public List findSubmissionWorkIdByActivityId(String activityId)
			throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select s.id,s.staff_id,s.sw_state,f.user_name,s.time_limit,s.create_date,s.update_date  from dc_submission_work s ")
				.append(
						" left join frameuser f on s.staff_id=f.user_code  where s.act_id = ? and sw_state <> 8 and sw_state <> 6 and sw_type <> 8 ");

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, activityId));
		List list = null;
		try {
			list = new ArrayList();
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					TaskTrackDetails treeNode = new TaskTrackDetails();
					String id = rs.getFieldValueAsString("id");
					treeNode.setId(id);
					treeNode.setUiProvider("col");
					int state = rs.getFieldValueAsInteger("sw_state")
							.intValue();
					treeNode.setStatus(state);
					String stateStr = "";
					switch (state) {
					case 1:
						stateStr = "已填写未上报";
						break;
					case 2:
						stateStr = "已提交等待其他人";
						break;
					case 3:
						stateStr = "超时未完成";
						break;
					case 4:
						stateStr = "等待审批中";
						break;
					case 5:
						stateStr = "完成";
						break;
					case 7:
						stateStr = "审批未通过";
						break;
					default:
						stateStr = "未处理";
						break;
					}
					String userName = rs.getFieldValueAsString("user_name");
					treeNode.setText(userName);
					treeNode.setLeaf(true);
					treeNode.setIconCls("collectionUserGroup");
					treeNode.setStatusInfo(stateStr);
					
					Date upDate = rs.getFieldValueAsDate("update_date");
					String upDateStr = Format.getInstance().dateToString(upDate);
					treeNode.setCompleteDate(upDateStr);
					
					Date creDate = rs.getFieldValueAsDate("create_date");
					String creDateStr = Format.getInstance().dateToString(creDate);
					treeNode.setCreateDate(creDateStr);
					
					treeNode.setTimeLimit(rs.getFieldValueAsString("time_limit"));
					
					treeNode.setType(22);

					list.add(treeNode);

					rs.next();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("findSubmissionWorkIdByActivityId error!");
		}
		return list;
	}

	public List findCompleteSubmissionWorkByUser(String userCode)
			throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select s.id,s.proc_id,t.item_name,w.wf_instance_desc,w.wf_name,s.create_date,")
				.append(
						"s.act_id,s.staff_id,s.update_date,s.form_id,s.sw_state,s.sw_name ")
				.append(
						" from dc_item_info t left join dc_submission_work s on s.proc_id = t.id ")
				.append(
						" left join dc_wf_instance w on t.id = w.proc_id  where s.staff_id = ? and sw_state <> 0 ")
				.append(
						"  and  sw_state <> 1 and  sw_state <> 3 and sw_state <> 6 and sw_state <> 7 and sw_state <> 8 and sw_type <> 8 ");

		List submissionWorkList = null;

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, userCode));

		try {
			submissionWorkList = new ArrayList();
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					// SubmissionWorkItem swi = new SubmissionWorkItem();
					TaskInfo swi = new TaskInfo();
					swi.setId(rs.getFieldValueAsString("id"));
					swi.setProcId(rs.getFieldValueAsString("proc_id"));
					swi.setProcName(rs.getFieldValueAsString("item_name"));
					swi.setTaskDesc(rs
							.getFieldValueAsString("wf_instance_desc"));
					swi.setTaskName(rs.getFieldValueAsString("wf_name"));
					swi.setActId(rs.getFieldValueAsString("act_id"));
					swi.setType(Constants.TASK_TYPE_SUBMISSIONWORK);
					swi.setStaffId(rs.getFieldValueAsString("staff_id"));
					Date upDate = rs.getFieldValueAsDate("update_date");
					String upDateStr = Format.getInstance().dateToString(upDate);
					swi.setUpDateStr(upDateStr);
					Date creDate = rs.getFieldValueAsDate("create_date");
					String creDateStr = Format.getInstance().dateToString(creDate);
					swi.setCreateDate(creDateStr);
					swi.setFormId(rs.getFieldValueAsString("form_id"));
					swi.setState(rs.getFieldValueAsInteger("sw_state")
							.intValue());
					swi.setPreActName(rs.getFieldValueAsString("sw_name"));

					submissionWorkList.add(swi);

					rs.next();
				}

				rs.clearAll();
			}

		} catch (Exception e) {
			logger.error("查找用户编码为：" + userCode + "的已办采集任务失败！", e);
			throw new DaoException("查找用户编码为：" + userCode + "的已办采集任务失败！");
		}

		return submissionWorkList;
	}

	/**
	 * 获取该报送环节中的所有报送任务的id
	 * 
	 * @param actId
	 * @return
	 * @throws DaoException
	 */
	public String getActAllSubWorkIds(String actId) throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select id from dc_submission_work where act_id=? and sw_state <> 3 and  sw_state <> 5 ")
				.append(
						"  and  sw_state <> 6 and sw_state <> 8 and sw_state <> 9 and sw_type <> 8 ");
		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, actId));
		StringBuffer subWorkIds = new StringBuffer();
		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					String id = rs.getFieldValueAsString("id");
					if (subWorkIds.length() == 0) {
						subWorkIds.append(";").append(id).append(";");
					} else {
						subWorkIds.append(id).append(";");
					}

					rs.next();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			throw new DaoException("getActAllSubWorkIds throw error!");
		}
		return subWorkIds.toString();

	}

	private void getAllSubWorksByAct2(String subWorkActId, List allInfo,
			Connection conn) throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select f.user_name ,d.id,d.sw_name,d.act_id,d.sw_state,d.sw_type,d.staff_id,d.form_id,d.proc_id ")
				.append(
						" from dc_submission_work d left join frameuser f on d.staff_id = f.user_code where d.act_id=? ")
				.append(
						"  and d.sw_state <> 0 and d.sw_state <> 1 and d.sw_state <>2 and d.sw_state <>3 and d.sw_state <>6 ")
				.append(
						"  and d.sw_state <>7 and d.sw_state <>8 and d.sw_state <>9 and d.sw_type <> 8 ");

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, subWorkActId));
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);

		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					SubmissionWorkItem swi = new SubmissionWorkItem();
					swi.setStatffName(rs.getFieldValueAsString("user_name"));
					swi.setId(rs.getFieldValueAsString("id"));
					swi.setTaskName(rs.getFieldValueAsString("sw_name"));
					swi.setActId(rs.getFieldValueAsString("act_id"));
					swi
							.setType(rs.getFieldValueAsInteger("sw_type")
									.intValue());
					swi.setStaffId(rs.getFieldValueAsString("staff_id"));
					swi.setFormId(rs.getFieldValueAsString("form_id"));
					swi.setProcId(rs.getFieldValueAsString("proc_id"));
					
					allInfo.add(swi);

					rs.next();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getActAllSubWorks throw error!");
		}

	}

	private SubmissionWorkItem getSubWorks4ApproveByAct(String subWorkActId,
			Connection conn) throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select f.user_name,d.id,d.sw_name,d.act_id,d.sw_state,d.sw_type,d.staff_id,d.form_id,d.proc_id ")
				.append(
						" from dc_submission_work d left join frameuser f on d.staff_id = f.user_code ")
				.append(" where d.act_id=? and d.sw_type =8 ");

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, subWorkActId));
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);
		SubmissionWorkItem swi = null;
		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {
					swi = new SubmissionWorkItem();
					swi.setStatffName(rs.getFieldValueAsString("user_name"));
					swi.setId(rs.getFieldValueAsString("act_id"));
					swi.setTaskName(rs.getFieldValueAsString("sw_name"));
					swi.setActId(rs.getFieldValueAsString("act_id"));
					swi
							.setType(rs.getFieldValueAsInteger("sw_type")
									.intValue());
					swi.setStaffId(rs.getFieldValueAsString("staff_id"));
					swi.setFormId(rs.getFieldValueAsString("form_id"));
					swi.setProcId(rs.getFieldValueAsString("proc_id"));

				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getActAllSubWorks throw error!");
		}
		return swi;
	}

	public List getAllSubWorksByAct(String procId, String actId,
			int currentOrParrent) throws DaoException {
		Connection conn = null;
		StringBuffer sqlString = new StringBuffer();

		if (currentOrParrent == Constants.DATACOLLECTVIEW_REQUEST_TYPE_SUBMIDATA) {
			sqlString
					.append(
							"select id,para_id,act_type,act_name,appRole_Or_urgDate,proc_id,")
					.append(
							"examRol_Or_colRol from dc_proc_instance where item_id=? and id=?  ");
		} else if (currentOrParrent == Constants.DATACOLLECTVIEW_REQUEST_TYPE_COLLECT) {
			SubmissionWorkItem submissionWorkItem = this
					.getSubWorks4ApproveByAct(actId, conn);
			if (submissionWorkItem != null) {
				List list = new ArrayList();
				list.add(submissionWorkItem);
				return list;
			}

			sqlString
					.append(
							"select id,para_id,act_type,act_name,appRole_Or_urgDate,proc_id,")
					.append(
							"examRol_Or_colRol from dc_proc_instance where item_id=? and para_id=? ");
		}
		List activityList = null;
		try {
			conn = this.getConnection();
			activityList = new ArrayList();
			this.getActivities(conn, procId, actId, sqlString.toString(),
					activityList);
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException(Constants.SEARCH
					+ "getAllSubWorksByAct tree" + Constants.FAIL);
		} finally {
			DBUtils.close(conn);
		}
		return activityList;
	}

	public List getAllSubWorksByAct(String procId, String actId,
			int currentOrParrent, int actType) throws DaoException {
		Connection conn = null;
		StringBuffer sqlString = new StringBuffer();

		if (currentOrParrent == Constants.DATACOLLECTVIEW_REQUEST_TYPE_SUBMIDATA) {
			if (actType == 1) {
				sqlString
						.append(
								"select id,para_id,act_type,act_name,appRole_Or_urgDate,")
						.append(
								"examRol_Or_colRol from dc_proc_instance where item_id=? and para_id=? ");
			} else {
				sqlString
						.append(
								"select id,para_id,act_type,act_name,appRole_Or_urgDate,")
						.append(
								"examRol_Or_colRol from dc_proc_instance where item_id=? and id=?  ");
			}

		} else if (currentOrParrent == Constants.DATACOLLECTVIEW_REQUEST_TYPE_COLLECT) {
			sqlString
					.append(
							"select id,para_id,act_type,act_name,appRole_Or_urgDate,")
					.append(
							"examRol_Or_colRol from dc_proc_instance where item_id=? and para_id=? ");
		}
		List activityList = null;
		try {
			conn = this.getConnection();
			activityList = new ArrayList();
			this.getActivities(conn, procId, actId, sqlString.toString(),
					activityList);
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException(Constants.SEARCH
					+ "getAllSubWorksByAct tree" + Constants.FAIL);
		} finally {
			DBUtils.close(conn);
		}
		return activityList;
	}

	private void getActivities(Connection conn, String processId,
			String paraId, String sql, List allInfo) throws DaoException {
		logger.info(Constants.INTOMETHOD + "getActivities");
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, processId);
			ps.setString(2, paraId);
			rs = ps.executeQuery();

			while (rs.next()) {
				int activityType = rs.getInt("act_type");
				String id = rs.getString("id");
				String text = rs.getString("act_name");

				switch (activityType) {
				case 0:
					SubmissionWorkItem swi = new SubmissionWorkItem();
					swi.setFormId("");
					swi.setTaskName(text);
					swi.setActId(id);
					swi.setType(0);
					swi.setProcId(processId);

					// 递归调用
					this.getActivities(conn, processId, id, sql, allInfo);

					break;
				case 1:
					SubmissionWorkItem approveSwi = new SubmissionWorkItem();
					approveSwi.setFormId("");
					approveSwi.setTaskName(text);
					approveSwi.setActId(id);
					approveSwi.setType(1);
					approveSwi.setStatffName(text);
					approveSwi.setProcId(processId);

					SubmissionWorkItem submissionWorkItem = this
							.getSubWorks4ApproveByAct(id, conn);
					if (submissionWorkItem != null) {
						allInfo.add(submissionWorkItem);
					} else {
						// 递归调用
						this.getActivities(conn, processId, id, sql, allInfo);
					}
					break;
				case 2:

					this.getAllSubWorksByAct2(id, allInfo, conn);

					break;
				}

			}
			logger.debug(Constants.SEARCH + "processinfo tree"
					+ Constants.SUCCESS);

		} catch (Exception e) {
			logger.error("getActivities() of throws : ", e);
			throw new DaoException(Constants.SEARCH + "监控流程实例信息"
					+ Constants.FAIL);
		} finally {
			DBUtils.close(rs, ps);
		}

	}

	public List findAllSubmissionWorkByUser(String userCode)
			throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select s.id,s.proc_id,t.item_name,w.wf_instance_desc,w.wf_name,")
				.append(
						"s.act_id,s.staff_id,s.update_date,s.form_id,s.sw_state,s.sw_name ")
				.append(
						" from dc_item_info t left join dc_submission_work s on s.proc_id = t.id ")
				.append(
						" left join dc_wf_instance w on t.id = w.proc_id  where s.staff_id = ? and sw_type <> 8  ")
				.append("  and sw_state <> 6  and sw_state <> 8");

		List submissionWorkList = null;

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, userCode));

		try {
			submissionWorkList = new ArrayList();
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					// SubmissionWorkItem swi = new SubmissionWorkItem();
					TaskInfo swi = new TaskInfo();
					swi.setId(rs.getFieldValueAsString("id"));
					swi.setProcId(rs.getFieldValueAsString("proc_id"));
					swi.setProcName(rs.getFieldValueAsString("item_name"));
					swi.setTaskDesc(rs
							.getFieldValueAsString("wf_instance_desc"));
					swi.setTaskName(rs.getFieldValueAsString("wf_name"));
					swi.setActId(rs.getFieldValueAsString("act_id"));
					swi.setType(Constants.TASK_TYPE_SUBMISSIONWORK);
					swi.setStaffId(rs.getFieldValueAsString("staff_id"));
					Date upDate = rs.getFieldValueAsDate("update_date");
					String upDateStr = Format.getInstance().dateToYMD(upDate);
					swi.setUpDateStr(upDateStr);
					swi.setFormId(rs.getFieldValueAsString("form_id"));
					swi.setState(rs.getFieldValueAsInteger("sw_state")
							.intValue());
					swi.setPreActName(rs.getFieldValueAsString("sw_name"));
					submissionWorkList.add(swi);

					rs.next();
				}

				rs.clearAll();
			}

		} catch (Exception e) {
			logger.error("查找用户编码为：" + userCode + "的已办采集任务失败！", e);
			throw new DaoException("查找用户编码为：" + userCode + "的已办采集任务失败！");
		}

		return submissionWorkList;
	}

	public SubmissionWorkItem getByKey(String id) throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"select id,proc_id,sw_desc,sw_name,act_id,sw_state,sw_type,staff_id,time_limit, ")
				.append(" form_id from dc_submission_work where id=? ");

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, id));
		SubmissionWorkItem swi = new SubmissionWorkItem();
		try {
			query.access();
			if (query.resultSetAvailable()) {

				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					swi.setId(rs.getFieldValueAsString("id"));
					swi.setProcId(rs.getFieldValueAsString("proc_id"));
					swi.setTaskDesc(rs.getFieldValueAsString("sw_desc"));
					swi.setTaskName(rs.getFieldValueAsString("sw_name"));
					swi.setActId(rs.getFieldValueAsString("act_id"));
					swi.setState(rs.getFieldValueAsInteger("sw_state")
							.intValue());
					swi
							.setType(rs.getFieldValueAsInteger("sw_type")
									.intValue());
					swi.setStaffId(rs.getFieldValueAsString("staff_id"));
					swi.setTimeLimitStr(rs.getFieldValueAsString("time_limit"));
					swi.setFormId(rs.getFieldValueAsString("form_id"));

					rs.next();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("获取ID为：" + id + " 的报送任务明细出错！");
		}
		return swi;
	}

	public boolean saveByTransmit(SubmissionWorkItem swi, String receiveUsers)
			throws DaoException {

		String sql = this.sqlInsert();

		UpdateOperator update = new UpdateOperator();
		update.setSql(sql);
		Connection conn = null;
		try {
			conn = this.getConnection();
			update.setUseOnlyConnectionFlag(true);
			update.setPresentConnection(conn);
			String[] userCodes = StringUtils.split(receiveUsers, ",");
			if (userCodes != null && userCodes.length > 0) {
				UrgencyManager um = new UrgencyManager();
				SmsManager sm = new SmsManager();
				for (int j = 0; j < userCodes.length; j++) {
					String userCode = userCodes[j];

					SqlParameterSet spSet = new SqlParameterSet();
					String id = String.valueOf(this
							.getSeq("dc_submission_work"));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR, id));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR, swi
							.getProcId()));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR, swi
							.getTaskDesc()));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR, swi
							.getTaskName()));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR, swi
							.getActId()));
					spSet.addParameter(new SqlParameter(SqlType.INTEGER,
							new Integer(0)));
					spSet.addParameter(new SqlParameter(SqlType.INTEGER,
							new Integer(swi.getType())));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR,
							userCode));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR, swi
							.getTimeLimitStr()));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR, swi
							.getUrgeDateStr()));
					spSet.addParameter(new SqlParameter(SqlType.VARCHAR, swi
							.getFormId()));

					// 把提醒信息保存到短信表里，进行短信通知
					Urgency uc = um.getBykey(swi.getActId(), conn);
					String msg = uc.getRemindInfo();
					if(!StringUtils.isEmpty(msg)) {
						sm.saveSMS(conn, msg, userCode);
					}

					update.addBatchParameter(spSet);
				}
				update.access();
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("转发生成采集步骤明细信息失败！");
		} finally {
			DBUtils.close(conn);
		}

		int[] effectCount = update.getBatchEffectCounts();
		if (effectCount != null && effectCount.length > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("saveByTransmit:" + Constants.SAVE + "转发采集明细信息"
						+ Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("saveByTransmit:" + Constants.SAVE + "转发采集明细信息"
						+ Constants.FAIL);
			}
			return false;
		}

	}

	public boolean iSubWorkCommit(String id) throws DaoException {
		boolean flag = true;
		int state = this.getState(id);
		if (state == Constants.SUBMISSION_WAIT
				|| state == Constants.SUBMISSION_NOTSUBMIT
				|| state == Constants.SUBMISSION_DISACCORD) {
			flag = false;
		}
		return flag;
	}
	
//	public boolean iSubWorkCommit(String id) throws DaoException {
//		String sql = "select sw_state from dc_submission_work where id = ?";
//
//		boolean flag = true;
//		int state = 0;
//		QueryOperator query = new QueryOperator();
//		query.setSql(sql.toString());
//		query.addParameter(new SqlParameter(SqlType.VARCHAR, id));
//		try {
//			query.access();
//		} catch (Exception e) {
//			logger.error("", e);
//			throw new DaoException("iSubWorkCommit throw error!");
//		}
//		if (query.resultSetAvailable()) {// 检查结果集是否可用
//			// 获取并处理记录集
//			RsDataSet rs = new RsDataSet(query.getSqlResultSet());
//			if (rs.rowCount > 0) {
//				state = rs.getFieldValueAsInteger("sw_state").intValue();
//				if (state == Constants.SUBMISSION_WAIT || state == Constants.SUBMISSION_NOTSUBMIT || state == Constants.SUBMISSION_DISACCORD) {
//					flag = false;
//				}
//			}
//			rs.clearAll();
//		}
//		return flag;
//	}

	public int getState(String id) throws DaoException {
		String sql = "select sw_state from dc_submission_work where id = ?";
		int state = 0;
		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, id));
		try {
			query.access();
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getState throw error!");
		}
		if (query.resultSetAvailable()) {// 检查结果集是否可用
			// 获取并处理记录集
			RsDataSet rs = new RsDataSet(query.getSqlResultSet());
			if (rs.rowCount > 0) {
				state = rs.getFieldValueAsInteger("sw_state").intValue();
			}
			rs.clearAll();
		}
	
		return state;
	}
}
